package com.wuda.servlet.user;

import com.wuda.bean.BorrowRecord;
import com.wuda.dao.BorrowRecordDao;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;


@WebServlet("/user/addBorrowRecord")
public class AddBorrowRecord extends HttpServlet {
	BorrowRecordDao borrowRecordDao = new BorrowRecordDao();


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf8");

		int userId = Integer.parseInt(req.getParameter("userId"));
		int bookId = Integer.parseInt(req.getParameter("bookId"));

		BorrowRecord borrowRecord = new BorrowRecord();
		borrowRecord.setUserId(userId);
		borrowRecord.setBookId(bookId);
		borrowRecord.setBorrowDate(new Date());

		System.out.println("借书参数：bookId:" + bookId + ",userId:"+userId);

		int result = borrowRecordDao.addBorrowRecord(borrowRecord);



		JSONObject jsonResult = new JSONObject();
		jsonResult.put("code", result);
		switch (result) {
			case 200:
				jsonResult.put("msg", "借书成功");
				break;
			case 201:
				jsonResult.put("msg", "借书失败，书不存在");
				break;
			case 202:
				jsonResult.put("msg", "借书失败，该图书库存不足");
				break;
			case 203:
				jsonResult.put("msg", "借书失败，用户已经借了这本书");
				break;
			default:
				jsonResult.put("msg", "系统错误");
				break;
		}
		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}
	}


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
